<script setup>
import { onMounted, reactive, ref, provide } from 'vue'
import TabHead from './components/TabHead.vue'
import TableBody from './components/TableBody.vue'
import EditAndAdd from './components/EditAndAdd.vue'
import XqDrawer from './components/XqDrawer.vue'
import api from '@/api/index.js'
import { getOptions } from '@/utils'
import dayjs, { Dayjs } from 'dayjs'
import { filesExport } from '@/utils/filesTool.js'
import 'dayjs/locale/zh-cn'
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN'
dayjs.locale('zh-cn')
const props = defineProps({
  // 父组件要求的默认筛选参数
  params: { type: Object, default: () => ({}) }
})
// 加载状态
const loading = ref(false)
// 分页参数
const pageInfo = reactive({ current: 1, size: 10, total: 0 })
// 表格数据
const tableData = ref([])
// 抽屉节点
const drawer = ref()
// 当前数据保存
const curRow = ref({})
//弹框
const open = ref(false)
// 初始化
const init = (params) => {
  pageInfo.current = 1
  pageInfo.size = 10
  pageInfo.total = 0
  getList(params)
}
const pagesNum = ref()
// 获取表格数据
const getList = async (params = {}) => {
  loading.value = true
  const data = {
    ...pageInfo,
    ...props.params,
    ...params
  }
  const {
    data: { records, total, pages }
  } = await api.getFarList(data)
  pageInfo.total = total
  tableData.value = records
  loading.value = false
  pagesNum.value = pages
}

// 新增数据
const addItem = () => {
  curRow.value = {}
  drawer.value.open()
}

// 派单
const pd = (item) => {
  curRow.value = item
  drawer.value.open()
}

// 编辑数据
const xqDrawer = ref()
const xq = (item) => {
  curRow.value = item
  xqDrawer.value.open()
}

// 关闭弹窗处理
const closeDrawer = () => {
  curRow.value = {}
}
// 页码变化
const pageChange = (page) => {
  pageInfo.current = page
  getList(savePara.value)
}
// 搜索
const savePara = ref({})
const search = (params) => {
  savePara.value = params
  init(params)
}

//选择的时间范围
const value1 = ref(dayjs('', 'YYYY-MM-DD'))
//弹框组件
const handleOk = async () => {
  var allList = []
  var params = savePara.value
  var data = {
    current: 1,
    size: pageInfo.total,
    total: 0,
    ...params
  }
  const {
    data: { records, total, pages }
  } = await api.getFarList(data)
  data.total = total
  allList.push(...records)
  //根据时间排序
  allList.sort((a, b) => new Date(b.details[0].startTime) - new Date(a.details[0].startTime))
  allList = allList.filter((order) => {
    const time1 = value1.value[0] ? value1.value[0].toISOString().split('T')[0] : null
    const time2 = value1.value[0] ? value1.value[1].toISOString().split('T')[0] : null
    return (
      (!time1 || order.details[0].startTime >= time1) &&
      (!time2 || order.details[0].startTime <= time2)
    )
  })
  console.log(getOptions('machine_type'), getOptions('field_type'))
  const GzList = getOptions('machine_type')
  const TdList = getOptions('field_type')

  const list = allList.map((order) => ({
    工单编号: order.details[0].orderNo ?? '无',
    耕作类型: GzList.filter((item) => item.constValue === order.details[0].orderType)
      ? GzList.filter((item) => item.constValue === order.details[0].orderType)[0].constLabel
      : '无',
    土地类型: TdList.filter((item) => item.constValue === order.details[0].fieldType)
      ? TdList.filter((item) => item.constValue === order.details[0].fieldType)[0]?.constLabel
      : '无',
    // order.details[0].fieldType === 1 ? '水田' : order.details[0].fieldType === 2 ? '旱田' : '无',
    开始时间: order.details[0].startTime ?? '无',
    接单人: order.receiveUserName ?? '无',
    '加油数量（升）': order.farmingWorkOrderFuel?.fuelValue ?? '无',
    '加油金额（元）': order.farmingWorkOrderFuel?.fuelMoney ?? '无',
    '作业单价（元）': order.realityFarmingPrice ?? '无',
    '作业面积（亩）': order.realityFarmingArea ?? '无',
    '作业金额（元）': order.finalSettlementMoney ?? '无',
    '机手提成（元）': order.finalSettlementMoney ? order.finalSettlementMoney * 0.1 : '无',
    作业地点: order.details[0].farmingAddress ?? '无',
    备注: order.details[0].settlementRemark ?? '无'
  }))
  // console.log(list)
  filesExport(list, '工单详情')
  //后端接口
  // const time1 = value1.value[0] ? value1.value[0].toISOString().split('T')[0] : null
  // const time2 = value1.value[0] ? value1.value[1].toISOString().split('T')[0] : null
  // let list = savePara.value
  // savePara.value = {
  //   ...list,
  //   startTime: time1,
  //   endTime: time2
  // }
  // const {
  //   data: { url, name }
  // } = await api.exportGz(savePara.value)
  // window.open(url, '_blank').focus()
  value1.value = ''
  open.value = false
}

//数据导出
const exportToExcel = () => {
  open.value = true
}

onMounted(() => {
  init()
})
provide('tableData', tableData)
</script>

<template>
  <a-spin :spinning="loading" wrapperClassName="com-spin">
    <div class="com-full page">
      <div class="head">
        <TabHead
          @add="addItem"
          @exportToExcel="exportToExcel"
          @init="search({})"
          @search="search"
        />
      </div>
      <a-modal v-model:open="open" width="1000px" title="数据导出" @ok="handleOk">
        <p>选择时间范围(不选则表示导出全部工单详情)</p>
        <a-range-picker v-model:value="value1" format="YYYY-MM-DD" />
      </a-modal>
      <div class="table">
        <TableBody
          :total="pageInfo.total"
          @pageChange="pageChange"
          :pageNum="pageInfo.current"
          @xq="xq"
          @pd="pd"
          @reload="getList(saveParams)"
        />
      </div>
    </div>
    <EditAndAdd
      ref="drawer"
      :faMenuSltOpt="tableData"
      :curRow="curRow"
      @close="closeDrawer"
      @init="search({})"
      @reload="getList(saveParams)"
    />
    <XqDrawer
      ref="xqDrawer"
      :curRow="curRow"
      @close="closeDrawer"
      @init="search({})"
      @reload="getList(saveParams)"
    />
  </a-spin>
</template>

<style lang="scss" scoped>
.page {
  display: flex;
  flex-direction: column;
  gap: 24px;

  .table {
    flex: 1;
    overflow: auto;
  }
}
</style>
